package com.yc.c112s3plyblog.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.upload.vo.Result;
import com.yc.c112s3plyblog.entity.Article;
import com.yc.c112s3plyblog.entity.Category;
import com.yc.c112s3plyblog.entity.User;
import com.yc.c112s3plyblog.service.IArticleService;
import com.yc.c112s3plyblog.service.impl.ArticleServiceImpl;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ly
 * @since 2022-10-12
 */
@RestController
@RequestMapping("/c112s3plyblog/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @PostMapping("save")
    public Result save(Article article,
                       // 从会话获取对象, 注入到该参数
                       @SessionAttribute Map<String,Object> loginedUser) {
        final String name = (String) loginedUser.get("name");
        article.setAuthor(name);
        // TODO 扩展: 用户没有填写简介, 那么使用文章内容提取少量文字作为简介
        articleService.saveOrUpdate(article);
        return new Result(1, "文章保存成功!", null);
    }

    @GetMapping("queryById")
    public Article queryById(int id){
        return articleService.getById(id);
    }


    @RequestMapping("queryByCid")
    public Page<Article> queryByCid(
            int cid,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size){
        // 构建分页对象
        Page<Article> p = new Page<>(page,size);
        // 构建条件对象
        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Article::getCategoryId, cid);
        return articleService.page(p,lqw);
    }

}

